﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BySoft.Server.Common.Schema;
using BySoft.Server.Common;
using BySoft.Web.Utility;
using BySoft.Server.Consts;
using BySoft.Server.Business;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Data;

namespace BySoft.Web.Site.SysManage
{
    public partial class ParamerterEdit : AuthBasePage
    {
        private String OLDPARAMETERName_FLAG = "OLDPARAMETERNAME_FLAG";//旧的参数的标志,viewSate的key值
        
        #region ID
        /// <summary>
        ///  参数ID 
        /// </summary>
        protected int ParameterID
        {
            get
            {
                int result = 0;
                if (ViewState[SysParameterTable.C_PARAMETERID] == null)
                {
                    if (Request["ID"] != null && Request["ID"].ToString() != "")
                    {
                        //divheadtxt.InnerHtml = "<div class=\"breadcrumb\">系统管理 >><a href=" + "ParamerterList.aspx" + ">参数管理</a>>>参数编辑</div>";
                        divheadtxt.InnerHtml = "<h1 class=\"tit\">系统管理 >> <a href=" + "ParamerterList.aspx" + ">参数管理</a> >> 编辑</h1>";
                        try
                        {
                            result = CommonMethod.ConvertToInt(Request["ID"].ToString());
                            ViewState[SysParameterTable.C_PARAMETERID] = result;
                        }
                        catch
                        {
                            throw new Exception("the ID is error!");
                        }
                    }
                    else
                    {
                        //divheadtxt.InnerHtml = "<div class=\"breadcrumb\">系统管理>><a href=" + "ParamerterList.aspx" + ">参数管理</a>>>参数新增</div>";
                        divheadtxt.InnerHtml = "<h1 class=\"tit\">系统管理 >> <a href=" + "ParamerterList.aspx" + ">参数管理</a> >> 新增</h1>";
                    }
                }
                else
                {
                    result = CommonMethod.ConvertToInt(ViewState[SysParameterTable.C_PARAMETERID]);
                }
                return result;
            }
        }
        #endregion

        #region Event
        /// <summary>
        ///  页面初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ParameterID > 0)
                {
                    LoadInfo();
                }
                else
                {
                    BindParameterType();//参数类别绑定
                }
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>iframeAutoFit();</script>");
            }

        }

        /// <summary>
        ///  确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOK_Click(object sender, EventArgs e)
        {

            if (CommonMethod.GetStringLength(txtValue.Text) > 10)
            {
                UIHelper.AlertMessage(this, string.Format(Message.MaxLengthInputString, "参数值", "10"));
                return;
            }
            bool bResult = false;
            if (ParameterID <= 0)//新增
            {
                if (SysParameter.isCodeExist(ddlType.SelectedValue, txtCode.Text.Trim()))
                {
                    UIHelper.AlertMessage(this.Page, String.Format(Message.Exists, "参数编号"));
                    return;
                }
                if (SysParameter.isNameExist(ddlType.SelectedValue, txtName.Text.Trim()))
                {
                    UIHelper.AlertMessage(this.Page, String.Format(Message.Exists, "参数名称"));
                    return;
                }

                SysParameterEntity newEntity = GetNewEntity();
                if (SysParameter.Insert(newEntity))
                {
                    bResult = true;
                    UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "/SysManage/ParamerterList.aspx");
                }
                else
                {
                    UIHelper.AlertMessage(this.Page, Message.SaveFail);
                }
                base.LogAction(BaseEnum.ActionType.Add, newEntity.ParameterID.Value.ToString(), bResult, null, new EntityBase[] { newEntity });
            }
            else//编辑
            {

                SysParameterEntity entity = new SysParameterEntity();
                entity.ParameterID = ParameterID;
                if ((String)ViewState[OLDPARAMETERName_FLAG] != txtName.Text.Trim() && SysParameter.isCodeExist(ddlType.SelectedValue, txtName.Text.Trim()))
                {
                    UIHelper.AlertMessage(this.Page, String.Format(Message.Exists, "参数名称"));
                    return;
                }
                GetData(entity);
                if (SysParameter.Update(entity))
                {
                    bResult = true;
                    UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "/SysManage/ParamerterList.aspx");
                }
                else
                {
                    UIHelper.AlertMessage(this.Page, Message.SaveFail);
                }
                base.LogAction(BaseEnum.ActionType.Modify, entity.ParameterID.Value.ToString(), bResult, null, new EntityBase[] { entity });
            }
        }
        #endregion

        #region method
        /// <summary>
        ///  加载参数数据
        /// </summary>
        private void LoadInfo()
        {
            SysParameterEntity entity = BySoft.Server.Business.SelectionCatche.GetParamerterByID(ParameterID);
            if (entity != null && entity.Status != ((int)BaseEnum.CommonSatus.Delete).ToString())
            {
                spanCode.Visible = false;
                spanType.Visible = false;
                lblType.Visible = true;
                lblCode.Visible = true;
                lblCode.Text = entity.ParameterCode;
                lblType.Text = SysParametertype.GetSysParametertypeByID(entity.ParameterTypeID).ParameterTypeName;
                txtIndex.Text = entity.OrderNumber.ToString();
                txtName.Text = entity.ParameterName;
                ViewState[OLDPARAMETERName_FLAG] = entity.ParameterName;//缓存旧的参数名称
                txtRemark.Text = entity.Description;
                trCreate.Visible = true;
                trModify.Visible = true;
                lblCreator.Text = SysUser.GetName(entity.CreateUserID);
                lblCreateDate.Text = entity.CreateDate == null ? "" : entity.CreateDate.Value.ToString(SystemConfig.DateFromat);
                lblModifyDate.Text = entity.ModifyDate == null ? "" : entity.ModifyDate.Value.ToString(SystemConfig.DateFromat);
                lblModifyUser.Text = SysUser.GetName(entity.ModifyUserID);
                txtValue.Text = entity.ParatmeterValue;
                cbValid.Checked = entity.Status == CommonConsts.YES ? true : false;

            }
            else
            {
                UIHelper.AlertMessageGoToURL(this.Page, "找不到相关记录！", "/SysManage/ParameterList.aspx");
            }
        }

        /// <summary>
        ///   获得新增参数的实体
        /// </summary>
        /// <returns></returns>
        private SysParameterEntity GetNewEntity()
        {
            SysParameterEntity entity = new SysParameterEntity();
            entity.CreateDate = DateTime.Now;
            entity.CreateUserID = CurrentUser.UserID;
            entity.ParameterTypeID = ddlType.SelectedValue;
            entity.ParameterCode = txtCode.Text.Trim();
            entity.Status = ((int)BaseEnum.CommonSatus.Started).ToString();
            GetData(entity);
            return entity;
        }

        /// <summary>
        ///  获得页面输入数据，编辑页面和新增页面共有的
        /// </summary>
        /// <param name="entity"></param>
        private void GetData(SysParameterEntity entity)
        {
            entity.ModifyUserID = this.CurrentUser.UserID;
            entity.ModifyDate = DateTime.Now;
            entity.Description = txtRemark.Text.Trim();
            entity.ParameterName = txtName.Text.Trim();
            entity.OrderNumber = txtIndex.Text.Trim() == "" ? 0 : CommonMethod.ConvertToInt(txtIndex.Text.Trim());
            entity.ParatmeterValue = txtValue.Text.Trim();
            entity.Status = cbValid.Checked ? ((int)BaseEnum.CommonSatus.Started).ToString() : ((int)BaseEnum.CommonSatus.stopped).ToString();
        }

        /// <summary>
        ///  参数类别数据绑定,控件ddlType的数据绑定
        /// </summary>
        private void BindParameterType()
        {
            DataTable dt = BySoft.Server.Business.SelectionCatche.GetParameterTypeAll();
            DataView dv = new DataView(dt);
            dv.RowFilter = SysParametertypeTable.C_STATUS + "=" + ((int)BaseEnum.CommonSatus.Started).ToString();
            ddlType.DataSource = dv;
            ddlType.DataTextField = SysParametertypeTable.C_PARAMETERTYPENAME;
            ddlType.DataValueField = SysParametertypeTable.C_PARAMETERTYPEID;
            ddlType.DataBind();
            //ddlType.Items.Insert(0, new ListItem("==请选择==", ""));
            UIHelper.InsertFirstItem(ddlType);
        }
        #endregion
    }
}
